<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, nextTick, PropType, toRefs } from 'vue'
import useSchema from './hooks/useSchema'
import { AllSchemas, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { CurdData } from '@/api/warehouse/types'
import { ref } from 'vue'
import { FieldEnum, SelectEnum } from '@/api/warehouse/types'
import { getFieldEnumApi } from '@/api/warehouse'
import { SchemaConfig } from '@/api/global/types'
import { getSelectEnumApi } from '@/api/warehouse'

defineOptions({
  name: 'WarehousetSave'
})

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const uploadList = reactive<string[]>([]) // 图片列表

const getSelectEnum = async () => {
  const res = await getSelectEnumApi()
  if (res) {
    warehouseselectEnum.value = res.data

    getFieldEnumApi({ field: 'all' })
      .then((res) => {
        warehousefieldEnum.value = res.data
        const schemaConfig: SchemaConfig = {
          fieldEnum: warehousefieldEnum.value,
          selectEnum: warehouseselectEnum.value
        }
        const { crudSchemas } = useSchema(toRefs(schemaConfig))
        const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

        // 合并新的数据，确保不改变原有数据的类型
        allSchemas.value = {
          formSchema: newSchemas.formSchema || []
        }
      })
      .catch((error) => {
        console.error('API call failed', error)
      })
  }
}

getSelectEnum()

const rules: FormRules = reactive({})

const warehousefieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化

const warehouseselectEnum = ref<SelectEnum>({})

const submit = async () => {
  const elForm = await getElFormExpose()
  const data = (await getFormData()) as any

  // 检查自提地址
  if (data && data.support_selfpickup === 1 && !data.pickup_address) {
    ElMessage.error('支持自提时，自提地址必填')
    return false
  }

  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    setValues({
      image: uploadList.join(',')
    })
    const formData = await getFormData()

    return formData
  }
}

watch(
  () => props.currentRow,
  async (currentRow) => {
    if (!currentRow) return

    await nextTick()
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
